package com.sqx.modules.chat.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.chat.dao.ChatContentDao;
import com.sqx.modules.chat.dao.ChatConversationDao;
import com.sqx.modules.chat.entity.ChatConversation;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.task.dao.HelpOrderDao;
import com.sqx.modules.task.entity.HelpOrder;
import com.sqx.modules.utils.LonLatUtil;
import com.sqx.modules.utils.SenInfoCheckUtil;
import org.apache.commons.lang3.StringUtils;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class Timer {

    @Autowired
    private UserService userService;

    @Resource
    private UserDao userDao;
    @Autowired
    private ChatContentDao chatContentDao;
    @Autowired
    private ChatConversationDao chatConversationDao;
    @Autowired
    private CommonInfoService commonInfoService;

    @Resource
    private HelpOrderDao helpOrderDao;


    @Scheduled(cron="0 */1 * * * ?")
    @Async
    public void sendMsg(){
        //获取超过一分钟未读的消息 进行小程序推送
        List<Map<String, Object>> maps = chatContentDao.selectChatContentCountByWx(1,0);
        String userTemplateId = commonInfoService.findOne(249).getValue();
        String shopTemplateId = commonInfoService.findOne(311).getValue();
        String masterTemplateId = commonInfoService.findOne(261).getValue();
        for(Map<String, Object> map:maps){
            String chatConversationId = String.valueOf(map.get("chatConversationId"));
            String userId = String.valueOf(map.get("userId"));
            String ccUserId = String.valueOf(map.get("ccUserId"));
            String ccFocusedUserId = String.valueOf(map.get("ccFocusedUserId"));
            String counts = String.valueOf(map.get("counts"));
            if(userId.equals(ccUserId)){
                userId=ccFocusedUserId;
            }else{
                userId=ccUserId;
            }
            if(StringUtils.isNotEmpty(userId) && !"null".equals(userId)){
                UserEntity userEntity = userService.selectUserById(Long.parseLong(userId));
                if(userEntity!=null && (userEntity.getIsSendMsg()==null || userEntity.getIsSendMsg()==1)){
                    if(StringUtils.isNotEmpty(chatConversationId) && !"null".equals(chatConversationId)){
                        ChatConversation chatConversation = chatConversationDao.selectById(Long.parseLong(chatConversationId));
                        if(chatConversation!=null){
                            chatConversation.setIsWxMsg(Integer.parseInt(userId));
                            chatConversationDao.updateById(chatConversation);
                        }
                    }
                    List<String> msgList=new ArrayList<>();
                    msgList.add("未读消息通知");
                    msgList.add("您有"+counts+"条未读消息，赶快上线查看吧！");
                    if(StringUtils.isNotEmpty(userEntity.getOpenId())){
                        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),userTemplateId,null,msgList,3);
                    }else if(StringUtils.isNotEmpty(userEntity.getMasterOpenId())){
                        SenInfoCheckUtil.sendMasterMsg(userEntity.getMasterOpenId(),masterTemplateId,msgList,3);
                    }else{
                        SenInfoCheckUtil.sendShopMsg(userEntity.getShopOpenId(),shopTemplateId,null,msgList,3);
                    }

                    if(StringUtils.isNotEmpty(userEntity.getClientid())){
                        userService.pushToSingle("未读消息通知","您有"+counts+"条未读消息，赶快上线查看吧！",userEntity.getClientid());
                    }


                }
            }
        }
        String msg = commonInfoService.findOne(250).getValue();
        String count = commonInfoService.findOne(251).getValue();
        List<Map<String, Object>> mapList = chatContentDao.selectChatContentCountByDx(Integer.parseInt(msg),Integer.parseInt(count));
        for(Map<String, Object> map:mapList){
            String chatConversationId = String.valueOf(map.get("chatConversationId"));
            String userId = String.valueOf(map.get("userId"));
            String ccUserId = String.valueOf(map.get("ccUserId"));
            String ccFocusedUserId = String.valueOf(map.get("ccFocusedUserId"));
            String counts = String.valueOf(map.get("counts"));
            if(userId.equals(ccUserId)){
                userId=ccFocusedUserId;
            }else{
                userId=ccUserId;
            }
            if(StringUtils.isNotEmpty(userId) && !"null".equals(userId)){
                UserEntity userEntity = userService.selectUserById(Long.parseLong(userId));
                if(userEntity!=null && (userEntity.getIsSendMsg()==null || userEntity.getIsSendMsg()==1)){
                    if(StringUtils.isNotEmpty(chatConversationId) && !"null".equals(chatConversationId)){
                        ChatConversation chatConversation = chatConversationDao.selectById(Long.parseLong(chatConversationId));
                        if(chatConversation!=null){
                            chatConversation.setIsSendMsg(Integer.parseInt(userId));
                            chatConversationDao.updateById(chatConversation);
                        }
                    }
                    userService.sendMsg(userEntity.getPhone(),"dx",Integer.parseInt(counts),userEntity.getUserType());
                }
            }
        }




    }
    @Scheduled(cron="0 */1 * * * ?")
    @Async
    public void sendDuanxin(){
        /*
         * 短信推送
         * */
        // 1.查询订单累积多少条给师傅和商家发送短信
        String value = commonInfoService.findOne(629).getValue();
        // 2.查询出所有的待接单订单 => 查询出所有的师傅和商家 =>  查询推送距离配置 => 判断是否已经符合推送短信的条件
        List<HelpOrder> helpOrders = helpOrderDao.selectList(new LambdaQueryWrapper<HelpOrder>().eq(HelpOrder::getStatus, 1));
        List<UserEntity> masterAndShop = userDao.getMasterAndShop();
        Integer distanceValue = Integer.parseInt(commonInfoService.findOne(628).getValue());
        if(helpOrders.size() >= Integer.parseInt(value)){
            // 3.遍历所有的待接单订单  => 根据订单的经纬度算出推送距离过滤掉不符合条件的商家和师傅 => 给师傅和商家推送短信
            for (HelpOrder helpOrder : helpOrders){
                // 3.1获取符合条件的商家和师傅
                List<UserEntity> filterList = masterAndShop.stream().filter(item -> {
                    GlobalCoordinates target = new GlobalCoordinates(Double.parseDouble(helpOrder.getLatitude()), Double.parseDouble(helpOrder.getLongitude()));
                    GlobalCoordinates source = new GlobalCoordinates(Double.parseDouble(item.getLatitude()), Double.parseDouble(item.getLongitude()));
                    Integer distance = (int) LonLatUtil.getDistanceMeter(target, source, Ellipsoid.Sphere);//计算两个经纬度之间的距离
                    return distance <= distanceValue * 1000;
                }).collect(Collectors.toList());

                // 3.2给师傅和商家推送短信

            }
        }
    }



}
